﻿package net.wangit.view.unit.grid;

import java.util.ArrayList;
import java.util.List;

import net.wangit.Element;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.util.Checker;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.element.ElementComponentHelper;
import net.wangit.view.element.util.ElementUtil;
import net.wangit.view.util.Html;


public final class Td {

	private static final String ICON_SORT_NONE = "/common/images/list/s0.png";
	private List elements;

	public Td(ElementComponent element) {
		elements = new ArrayList();
		addElement(element);
	}

	public void write(ActionContext ac, StringBuffer html, int rowIndex, Row row) {
		ElementComponent first = (ElementComponent) elements.get(0);
		ElementComponentHelper.setRowIndex(first, rowIndex);
		if (first.getCombineRows() > 0) {
			first.writeTd(ac, html, rowIndex);
			for (int i = 0; i < elements.size(); i++) {
				Element element = (Element) elements.get(i);
				element.write(ac, html, rowIndex, row);
			}

			html.append("</td>");
		}
	}

	public void writeListHead(ActionContext ac, StringBuffer html) {
		ElementComponent first = (ElementComponent) elements.get(0);
		int sort = first.getSort();
		writeListTdHead(html, ElementUtil.getAlias(first), sort);
		String name = ElementUtil.resolveName(ac, first);
		html.append(Checker.isEmpty(name) ? "&nbsp;" : name);
		if (sort != 0)
			html.append("<img src=\"").append("/common/images/list/s0.png")
					.append("\"/>");
		html.append("</td>");
	}

	public void addElement(ElementComponent element) {
		elements.add(element);
	}

	private void writeListTdHead(StringBuffer html, String name, int sort) {
		html.append("<td");
		if (sort != 0)
			html.append(" onclick=\"$fSort(this,'").append(name).append("',")
					.append(sort).append(")\" style=\"cursor:hand\"");
		ElementComponent element = (ElementComponent) elements.get(0);
		Html.setRowSpan(html, element.getTdRowSpan());
		Html.setColSpan(html, element.getTdColSpan());
		Html.setAlign(html, element.getTdAlign());
		Html.setVerticalAlign(html, element.getTdVerticalAlign());
		Html.setWidth(html, element.getTdWidth(), element.getTdWidthMode());
		Html.setHeight(html, element.getTdHeight(), element.getTdHeightMode());
		html.append(">");
	}
}
